import {reqGetCode, reqUserLogin, reqUserRegister,reqUserInfo,reqLogout} from "@/api"
import { setToken } from "@/utils/token"
// 登陆与注册模块
const state = {
    code: "",
    token:"" || localStorage.getItem("TOKEN"),
    userInfo:{}
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){ 
        state.userInfo = userInfo
    },
    // 清除自己本地的数据
    USERLOGOUT(state){
        state.token = "",
        state.userInfo = {},
        localStorage.removeItem("TOKEN")
    }
}
const actions = {
    // 获取验证码
    async getCode({commit},phone){
        let result = await reqGetCode(phone)
        // console.log(result);
        if(result.code == 200){
            commit("GETCODE",result.data)
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }

    },

    // 用户注册
    async userRegister({commit},user){
        let result = await reqUserRegister(user)
        if(result.code== 200){
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }
    },

    // 用户登陆
    async userLogin({commit},data){
        let result = await reqUserLogin(data)
        // console.log(result);
        // 服务器下发token，用户的唯一标识符
        if(result.code == 200){
            commit("USERLOGIN",result.data.token)
            setToken(result.data.token)
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
    
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        // console.log(result);
        if(result.code == 200){
            commit("GETUSERINFO",result.data)
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
    // 退出登陆
    async userLogout({commit}){
        let result = await reqLogout()
        if(result.code ==200){
            commit("USERLOGOUT")
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}